﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Threading.Tasks;
using Leo.Awesome.DictionaryManagement.Domain;

namespace Leo.Awesome.DictionaryManagement.DomainServices
{
    public class DictionaryItemDataSeeder : SectionDataSeeder
    {
        private readonly ISectionRepository sectionRepository;
        private readonly IDictionaryItemRepository dictionaryItemRepository;

        public DictionaryItemDataSeeder(ISectionRepository sectionRepository,
            IDictionaryItemRepository dictionaryItemRepository) 
            : base(sectionRepository)
        {
            this.sectionRepository = sectionRepository;
            this.dictionaryItemRepository = dictionaryItemRepository;
        }

        public override async Task SeedAsync(List<Section> sections, string domain = "default")
        {
            await base.SeedAsync(sections, domain);
            var dictionaries = sections.Where(x => x.IsSection == false)
                .ToList();
            if(!dictionaries.Any() )
            {
                return;
            }
            var dicCodes= dictionaries.Select(x=>x.Code).ToList();

            var existEntites = await dictionaryItemRepository.GetListAsync(x =>
            dicCodes.Contains(x.Code));

            var existCodes= existEntites.Select(x=>x.Code).ToList();
            var sectionsfromDb= await sectionRepository.GetListAsync();

            foreach (var dictionariyCode in dicCodes.Except(existCodes))
            {
                var dictionarity= dictionaries.FirstOrDefault(x => x.Code == dictionariyCode);
                if (dictionarity == null) 
                {
                    continue;
                }
                var parnt = sectionsfromDb
                    .FirstOrDefault(x => x.Id == dictionarity.ParentId);

                if (parnt != null)
                {
                    await dictionaryItemRepository.InsertAsync(new DictionaryItem
                    {
                        Name = dictionarity.Name,
                        Code = dictionarity.Code,
                        DictionaryId = parnt.Id,
                        IsEnabled = true,
                        IsSystem = true,
                    });
                }
            }
        }
    }
}
